package com.study.hot.rx

import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.study.base.BaseActivity
import com.study.hot.R
import com.study.hot.model.Product
import com.study.hot.rx.viewmodel.ProductViewModel
import com.study.hot.rx.views.ProductAdapter
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.addTo
import kotlinx.android.synthetic.main.activity_rx_java.*

/**
 * <pre>
 *     author : fauks
 *     time   : 2020/03/28
 *     desc   :
 * </pre>
 */
class RxJavaActivity : BaseActivity() {
    override fun generateLayoutId() = R.layout.activity_rx_java
    val compoDisposables: CompositeDisposable by lazy {
        CompositeDisposable()
    }

    val productViewModel: ProductViewModel by lazy {
        ViewModelProvider(this)[ProductViewModel::class.java]
    }

    lateinit var adapter: ProductAdapter

    override fun initView() {
        super.initView()

        useByRecycerView()
    }

    private fun useByRecycerView() {
        adapter = ProductAdapter(R.layout.recycler_product, R.layout.recycler_product_header, mutableListOf())
        rxJavaRv.adapter = adapter
        productViewModel.getProductList()
        productViewModel.product.observe(this, Observer {
            constructDatas(it)
        })
    }

    //构造Section数据
    private fun constructDatas(products: MutableList<Product>?) {
        val productSectionList: MutableList<ProductAdapter.ProductSection> = mutableListOf()
        Observable.fromIterable(products)
                .flatMap {
                    productSectionList.add(ProductAdapter.ProductSection(true, it.name))
                    Observable.fromIterable(it.productList)
                }.map {
                    ProductAdapter.ProductSection(it)
                }.doOnNext {
                    productSectionList.add(it)
                }.subscribe {
                    adapter.setNewData(productSectionList)
                }.addTo(compoDisposables)
    }

    override fun onDestroy() {
        super.onDestroy()
        compoDisposables.clear()
    }
}